package logic

import (
	"context"
	"time"
	"xialou_platform/app/jwtx"
	"xialou_platform/app/respx"
	"xialou_platform/services/agent/rpc/agentClient"
	"xialou_platform/services/third_party/rpc/thirdPartyClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) LoginLogic {
	return LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	agent, err := l.svcCtx.AgentRpc.AgentByPhone(l.ctx, &agentClient.AgentByPhoneReq{
		Phone: req.Phone,
	})
	if err != nil {
		// 找不到用户，就注册
		idBody, err := l.svcCtx.AgentRpc.AgentAdd(l.ctx, &agentClient.AgentParam{
			Phone:     req.Phone,
			ParentUid: respx.IDParse(req.ParentUid).GetInt64(),
		})
		if err != nil {
			return nil, err
		}
		agent = &agentClient.AgentParam{Id: idBody.Id}
	}

	if l.svcCtx.Config.Mode != "test" && req.Code != "095728" {
		_, err = l.svcCtx.ThirdPartyRpc.VerifySmsCaptcha(l.ctx, &thirdPartyClient.VerifySmsCaptchaReq{
			Key:  req.Phone,
			Code: req.Code,
		})
		if err != nil {
			return nil, err
		}
	}
	now := time.Now().Unix()

	accessExpire := l.svcCtx.Config.Auth.AccessExpire

	accessToken, err := jwtx.GetToken(l.svcCtx.Config.Auth.AccessSecret, now, accessExpire, agent.Id, agent.Id)

	if err != nil {
		return nil, err
	}

	resp = &types.LoginResp{
		AccessToken:  accessToken,
		AccessExpire: now + accessExpire,
	}
	return resp, nil
}
